<template>
  <div class="userMgr">
    <div class="action">
      <el-button plain type="primary" @click="capture">截屏</el-button>
<!--      <el-button plain type="primary" @click="exportFile">下载</el-button>-->
      <el-button plain type="primary" @click="createUser">新建用户</el-button>
      <el-button plain type="primary" @click="editUser" v-permission>编辑用户</el-button>
      <el-button plain type="primary" @click="deleteUser">删除用户</el-button>
      <el-button plain type="primary" @click="reFresh">刷新</el-button>
<!--      <p style="margin-left: 10px;color: rgb(156 156 156);">用户表 分页/不分页</p>-->
    </div>
    <div class="show_screen_shot" v-if="imgSrc" :class="isFull ? 'full' : ''">
      <div class="operate">
        <el-button link @click="saveImage"><i class="iconfont i-xiazai"></i> </el-button>
        <el-button link @click="view"><i class="iconfont " :class="!isFull ? 'i-quanping': 'i-tuichuquanping'"></i></el-button>
        <el-button link @click="imgSrc = ''"><i class="iconfont i-guanbi"></i> </el-button>
      </div>
      <img class="img" ref="img" :src="imgSrc" alt="">
    </div>
    <div class="table" ref="table">
      <div class="no_split_page" :style="{width: IsMobile ? '100%' : '48%'}">
        <vxe-grid v-bind="gridOptions" ref="noSplitPageTable"
                  @cell-click="cellClick"
        >
          <template #src_default="{ row, column }">
            <div style="display: flex;align-items: center;justify-content: space-between">
              <img style="width: 40px" :src="row.src"/>
              <el-upload
                  style="margin-left: 10px"
                  class="avatar-uploader"
                  :show-file-list="false"
                  :multiple="true"
                  ref="uploadPhoto"
                  :http-request="uploadImg"
              >
                <el-button circle link type="success"><i class="iconfont i-zhiding1"></i> </el-button>
              </el-upload>
            </div>
          </template>
        </vxe-grid>
      </div>
      <div class="split_page" v-if="!IsMobile">
        <vxe-grid v-bind="gridOptions1">
          <template #pager>
            <!--使用 pager 插槽  perfect 好看些-->
            <vxe-pager
                perfect
                :current-page="tablePage.currentPage"
                :page-size="tablePage.pageSize"
                :page-sizes="tablePage.pageSizes"
                :total="tablePage.total"
                :layouts="tablePage.layouts"
                @page-change="handlePageChange">
            </vxe-pager>
          </template>
        </vxe-grid>
      </div>
    </div>
    <Stepper
        ref="userStepper"
        :stepper-title="stepperTitle"
        :register-components="registerComponents"
        @closed="closed"
        @finished-step="finishedStep"></Stepper>
  </div>
</template>

<script setup>
import {computed, onMounted, reactive, ref} from "vue";
import {httpRequest} from "@/untils/httpRequest.ts";
import html2canvas from "html2canvas";
import {ElMessage, ElMessageBox} from "element-plus";
import Form1 from "./components/Form1";
import Form2 from "./components/Form2";
import Form3 from "./components/Form3";
import Stepper from "../../components/Stepper";
import {uploadFile} from "@/untils/uploadFile";
import {isMobile} from "@/untils/untils";


let leftCurrentClickRow = ref({})
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 5,
  pageSizes: [5,10,15,20],
  layouts: ['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']
})
const gridOptions = reactive({
  border: false,
  showOverflow: true,
  loading: false,
  height: 'auto',
  columnConfig: {
    resizable: true,
  },
  rowConfig: {
    height: 48,
    isCurrent: true,
    isHover: true
  },
  checkboxConfig: {
    checkMethod: checkMethod
  },
  columns: [
    {type: 'checkbox', width: 60},
    {field: 'id', title: 'ID', width: 50, align: 'center'},
    {field: 'src', title: 'photo', width: 80, align: 'center',slots: { default: 'src_default'}},
    {field: 'name', title: 'Name'},
    {field: 'account', title: 'Account'},
    {field: 'role', title: 'Role'},
    {field: 'createdAt', title: 'CreatedAt'},
    {field: 'updatedAt', title: 'UpdatedAt'},
  ],
  data: []
})
const gridOptions1 = reactive({
  border: false,
  showOverflow: true,
  loading: false,
  height: 'auto',
  columnConfig: {
    resizable: true,
  },
  rowConfig: {
    height: 48,
    isCurrent: true,
    isHover: true
  },
  checkboxConfig: {
    checkMethod: checkMethod
  },
  columns: [
    {type: 'checkbox', width: 60},
    {field: 'id', title: 'ID'},
    {field: 'name', title: 'Name'},
    {field: 'account', title: 'Account'},
    {field: 'role', title: 'Role'},
    {field: 'createdAt', title: 'CreatedAt'},
    {field: 'updatedAt', title: 'UpdatedAt'},
    {field: 'src', title: 'photo', align: 'center'}
  ],
  data: []
})

function checkMethod({ row }) {
  return row.is_action === "true";
}
const initView = () => {
  gridOptions.loading = true
  let params = {
    noSplitPage: true
  }
  httpRequest("post", "/user/getUser", null, params, "proxy").then(res => {
    if (res ?.data?.code === 200) {
      gridOptions.data = res.data?.data?.user || []
    }
    gridOptions.loading = false
  });
}

function findList() {
  gridOptions1.loading = true
  let params = {
    currentPage: tablePage.currentPage,
    pageSize: tablePage.pageSize,
  }
  httpRequest("post", "/user/getUser", null, params, "proxy").then(res => {
    if (res ?.data?.code === 200) {
      gridOptions1.data = res.data?.data?.user || []
      tablePage.total = res.data?.data?.tablePage?.total || 0
    }
    gridOptions1.loading = false
  });
}
function handlePageChange({ currentPage, pageSize }) {
  tablePage.currentPage = currentPage
  tablePage.pageSize = pageSize
  findList()
}
function reFresh() {
  initView()
  findList()
}

onMounted(()=>{
  reFresh()
})

let imgSrc = ref('')
let table = ref(null)
let img = ref(null)
let isFull = ref(false)
let timer = ref(null)

async function capture() {
  const canvas = await html2canvas(table.value, {
    // 配置选项
  });
  imgSrc.value = canvas.toDataURL();
}
function view() {
  if (timer.value) {
    clearTimeout(timer.value)
  }
  isFull.value = !isFull.value
}
function saveImage() {
  if (timer.value) {
    clearTimeout(timer.value)
  }
  // 设置延时器 超过300ms为单击 300ms内点击则为双击事件
  timer.value = setTimeout(() => {
    // 需要执行的逻辑代码...
    const link = document.createElement("a"); // 创建一个超链接对象实例
    link.download = "user.png"; // 设置要下载的图片的名称
    link.href = imgSrc.value; // 将图片的URL设置到超链接的href中
    link.click(); // 触发超链接的点击事件
  },300)
}
function exportFile() {
  let params = {
    fileName: '用户表'
  }
  httpRequest("POST", "/exportFile", null, params, "proxy", true, 'arraybuffer').then(res => {
    if (res && res.data) {
      let blob = new Blob([res.data], {
        // type: 'application/actet-stream;charset=utf-8'
        type: 'application/vnd.ms-excel'
      }); // 构造一个blob对象来处理数据，并设置文件类型
      let a = document.createElement('a'); // 生成一个a标签
      let href = window.URL.createObjectURL(blob); //创建下载的链接
      a.href = href; //指定下载链接
      let filename = ''
      let disposition = res.headers['content-disposition']
      let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      let matches = filenameRegex.exec(disposition);
      if (matches != null && matches[1]) {
        var names = matches[1].split("''");
        filename = names[names.length - 1];
        filename = decodeURIComponent(filename)
      }
      a.setAttribute('download', filename)
      document.body.appendChild(a); //把a标签加到页面中
      a.click(); //触发a标签下载
      document.body.removeChild(a); //下载完成移除元素
      window.URL.revokeObjectURL(href); //释放掉blob对象
      return
    }
  });
}

let uploadPhoto = ref(null)
const cellClick = ({row}) => {
  leftCurrentClickRow.value = row
}
const uploadImg = async (param) => {
  return new Promise((resolve, reject) => {
    uploadPhoto.value.clearFiles()
    if (param.file.name.split(".")[1] !== "png" && param.file.name.split(".")[1] !== "jpg") {
      ElMessage({
        message: "上传格式错误，不是.jpg格式或.png格式",
        type: "error",
      });
      return;
    }
    uploadFile(param.file, 0 , true).then(res => {
      if (res?.data?.code === 200) {
        let ctxFormData = ref({
          id: leftCurrentClickRow.value.id,
          account: leftCurrentClickRow.value.account,
          name: leftCurrentClickRow.value.name,
          role: leftCurrentClickRow.value.role,
          src: res.data.fileUrl
        })
        let editId = leftCurrentClickRow.value.id
        finishedStep(ctxFormData, editId)
        resolve(res.data.data)
      } else {
        ElMessage.error(res.data.msg)
      }
    })
  })
}

// 使用stepper案例
let registerComponents = [Form1,Form2,Form3]
let userStepper = ref(null)
let stepperTitle = ref('新建用户')
let noSplitPageTable = ref(null)
const IsMobile = computed(() => {
  // return isMobile()
  return true
});
const createUser = () => {
  userStepper.value.onShow(true)
}
const editUser = () => {
  let CheckboxRecords = getCheckboxRecords()
  if (CheckboxRecords.length !== 1 ) {
    ElMessage.warning('请选择一条数据进行操作')
    return
  }
  let selectRow = CheckboxRecords[0]
  stepperTitle.value = '编辑用户'
  userStepper.value.onShow(true,selectRow,true, selectRow.id)
}
const deleteUser = () => {
  let CheckboxRecords = getCheckboxRecords()
  if (CheckboxRecords.length === 0 ) {
    ElMessage.warning('请至少选择一条数据进行操作')
    return
  }
  ElMessageBox.confirm(
      '你确定要删除用户?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        let ids = CheckboxRecords.map(row => row.id)
        let params = {ids}
        httpRequest("POST", '/user/deleteUser', null, params, "proxy").then(res => {
          if (res?.data?.code === 200) {
            ElMessage.success(res?.data?.msg);
            reFresh()
          } else {
            ElMessage.error(res?.data?.msg);
          }
        });
      })
}
const getCheckboxRecords = () => {
  return noSplitPageTable.value.getCheckboxRecords()
}
const closed = () => {
}
const finishedStep = (ctxFormData,editId) => {
  let params = ctxFormData.value
  let url = '/user/addUser'
  if (editId) url = '/user/editUser'
  httpRequest("POST", url, null, params, "proxy").then(res => {
    if (res?.data?.code === 200) {
      ElMessage.success(res?.data?.msg);
      reFresh()
      userStepper.value.onShow(false)
    } else {
      ElMessage.error(res?.data?.msg);
    }
  });
}

</script>

<style scoped lang="less">
.userMgr {
  width: 100%;
  height: 100%;
  position: relative;
  .action {
    width: 100%;
    display: flex;
    margin-bottom: 16px;
    align-items: center;
  }
  .table {
    width: 100%;
    height: calc(100% - 48px);
    display: flex;
    justify-content: space-between;
    .no_split_page {
      width: 48%;
      height: 100%;
    }

    .split_page {
      width: 48%;
      height: 100%;
    }
  }
  .show_screen_shot{
    width: 30%;
    height: 40%;
    position: absolute;
    z-index: 999;
    left: 35%;
    top: 30%;
    .operate {
      position: absolute;
      left: 45%;
      bottom: 0;
      z-index: 9999;
      :deep(i) {
        color: #01e3f6;
      }
    }
    .img {
      width: 100%;
      height: 100%;
      position: absolute;
    }
  }
  .full {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 999;
    overflow: hidden;
  }

}
</style>